package cn.edu.scau.cmi.liujianxun.client.fxUI.hibernate;

import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.model.IdentifierGeneratorDefinition;
import org.hibernate.cfg.Configuration;

import cn.edu.scau.cmi.liujianxun.hibernate.domain.Student;
import cn.edu.scau.cmi.liujianxun.hibernate.domain.Teacher;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;

import javafx.scene.control.Button;

import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.control.TextArea;

import javafx.scene.control.ComboBox;

public class HibernateDemoController {
	@FXML
	private TextArea taResult;
	@FXML
	private ComboBox<String> cb1;
	@FXML
	private TextField tbID1;
	@FXML
	private TextField tbName1;
	@FXML
	private Button btAdd1;
	@FXML
	private Button btDel1;
	@FXML
	private Button btCheck1;
	@FXML
	private TextField tbName2;
	@FXML
	private TextField tbID2;
	@FXML
	private ComboBox<String> cb2;
	@FXML
	private Button btCheck2;
	@FXML
	private Button btChange2;
	@FXML
	private Button btchangeTutor3;
	@FXML
	private Button btShow3;
	@FXML
	private TextField tbTutor3;
	@FXML
	private TextField tbID3;
	@FXML
	private Button btCheck3;
	@FXML
	private Button btAddStudent4;
	@FXML
	private Button btShow4;
	@FXML
	private TextField tbStudentID4;
	@FXML
	private TextField tbID4;
	@FXML
	private Button btDelStudent4;
	@FXML
	private Button btCheck4;

	private static Configuration conf = new Configuration().configure();
	private static SessionFactory sessionFactory = conf.buildSessionFactory();
	
	public HibernateDemoController() {
	}
	
	public void init() {
		String s[] = {"教师", "学生"};
		cb1.getItems().addAll(s);
		cb2.getItems().addAll(s);
	}
	
	private void isExist(Long id, String type) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启事务
            //具体操作
            if(type.equals("教师")) {
            	Teacher t = session.load(Teacher.class, id);
            	taResult.appendText("工号：" + t.getId() + "   姓名：" + t.getName() + "\n");
            }
            else if(type.equals("学生")) {
            	Student s = session.load(Student.class, id);
            	taResult.appendText("学号：" + s.getId() + "   姓名：" + s.getName() + "\n");
            }
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            tx.rollback(); // 回滚事务
            taResult.appendText("不存在该成员！\n");
            throw e;
        } finally {
            session.close(); // 关闭session
        }
	}
	
	public void btAdd1Event(ActionEvent event) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启事务
            //具体操作
            String type = cb1.getValue();
            if(type.equals("教师")) {
            	Teacher t = new Teacher();
            	t.setName(tbName1.getText());
            	session.save(t);
            	tx.commit(); // 提交事务
            	taResult.appendText("添加成功！   工号：" + t.getId() + "   姓名：" + t.getName() + "\n");
            }
            else if(type.equals("学生")) {
            	Student s = new Student();
            	s.setName(tbName1.getText());
            	session.save(s);
            	tx.commit(); // 提交事务
            	taResult.appendText("添加成功！   学号：" + s.getId() + "   姓名：" + s.getName() + "\n");
            }
        } catch (RuntimeException e) {
            tx.rollback(); // 回滚事务
            taResult.appendText("添加失败！\n");
            throw e;
        } finally {
            session.close(); // 关闭session
        }
	}
	
	public void btCheck1Event(ActionEvent event) {
		String type = cb1.getValue();
		Long id = Long.valueOf(tbID1.getText());
		isExist(id, type);
	}
	
	public void btDel1Event(ActionEvent event) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启事务
            //具体操作
            String type = cb1.getValue();
            if(type.equals("教师")) {
            	Teacher t = session.load(Teacher.class, Long.valueOf(tbID1.getText()));
            	taResult.appendText("工号：" + t.getId() + "   姓名：" + t.getName() + "   删除成功！\n");
            	session.delete(t);
            }
            else if(type.equals("学生")) {
            	Student s = session.load(Student.class, Long.valueOf(tbID1.getText()));
            	taResult.appendText("学号：" + s.getId() + "   姓名：" + s.getName() + "   删除成功！\n");
            	session.delete(s);
            }
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            tx.rollback(); // 回滚事务
            taResult.appendText("不存在该成员，删除失败！\n");
            throw e;
        } finally {
            session.close(); // 关闭session
        }
	}
	
	public void btCheck2Event(ActionEvent event) {
		String type = cb2.getValue();
		Long id = Long.valueOf(tbID2.getText());
		isExist(id, type);
	}
	
	public void btChange2Event(ActionEvent event) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启事务
            //具体操作
            String type = cb2.getValue();
            if(type.equals("教师")) {
            	Teacher t = session.load(Teacher.class, Long.valueOf(tbID2.getText()));
            	t.setName(tbName2.getText());
            	session.update(t);
            }
            else if(type.equals("学生")) {
            	Student s = session.load(Student.class, Long.valueOf(tbID2.getText()));
            	s.setName(tbName2.getText());
            	session.update(s);
            }
            taResult.appendText("修改成功\n");
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            tx.rollback(); // 回滚事务
            taResult.appendText("不存在该成员，修改失败！\n");
            throw e;
        } finally {
            session.close(); // 关闭session
        }
	}
	
	public void btShow3Event(ActionEvent event) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启事务
            //具体操作
            Student s = session.load(Student.class, Long.valueOf(tbID3.getText()));
            taResult.appendText("学号：" + s.getId() + "   姓名：" + s.getName());
            if(s.getTeacher() != null)
            	taResult.appendText("   导师：" + s.getTeacher().getName() + "\n");
            else
            	taResult.appendText("   导师：无\n");
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            tx.rollback(); // 回滚事务
            taResult.appendText("不存在该成员！\n");
            throw e;
        } finally {
            session.close(); // 关闭session
        }
	}
	
	public void btCheck3Event(ActionEvent event) {
		String type = "教师";
		Long id = Long.valueOf(tbTutor3.getText());
		isExist(id, type);
	}
	
	public void btchangeTutor3Event(ActionEvent event) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启事务
            //具体操作
            Student s = session.load(Student.class, Long.valueOf(tbID3.getText()));
            Teacher t = session.load(Teacher.class, Long.valueOf(tbTutor3.getText()));
            s.setTeacher(t);
            taResult.appendText("修改成功！    学号：" + s.getId() + "   姓名：" + s.getName()
            					+ "   导师：" + s.getTeacher().getName() + "\n");
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            tx.rollback(); // 回滚事务
            taResult.appendText("修改失败，不存在该学生或教师！\n");
            throw e;
        } finally {
            session.close(); // 关闭session
        }
	}
	
	public void btShow4Event(ActionEvent event) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启事务
            //具体操作
            Teacher t = session.load(Teacher.class, Long.valueOf(tbID4.getText()));
            taResult.appendText("工号：" + t.getId() + "   姓名：" + t.getName());
            Set<Student> ss = t.getStudents();
            if(!ss.isEmpty()){
            	taResult.appendText("\n指导的学生：");
            	for (Student value : ss) {
            		taResult.appendText(value.getName() + " ");
                }
            	taResult.appendText("\n");
            }
            else
            	taResult.appendText("\n指导的学生：无\n");
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            tx.rollback(); // 回滚事务
            taResult.appendText("不存在该教师！\n");
            throw e;
        } finally {
            session.close(); // 关闭session
        }
	}
	
	public void btCheck4Event(ActionEvent event) {
		String type = "学生";
		Long id = Long.valueOf(tbStudentID4.getText());
		isExist(id, type);
	}
	
	public void btAddStudent4Event(ActionEvent event) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启事务
            //具体操作
            Teacher t = session.load(Teacher.class, Long.valueOf(tbID4.getText()));
            Set<Student> ss = t.getStudents();
            Student s = session.load(Student.class, Long.valueOf(tbStudentID4.getText()));
            if(s.getTeacher() == null) {
            	ss.add(s);
            	s.setTeacher(t);
                t.setStudents(ss);
                taResult.appendText("添加学生成功！\n");
                taResult.appendText("工号：" + t.getId() + "   姓名：" + t.getName());
                if(!ss.isEmpty()){
                	taResult.appendText("\n指导的学生：");
                	for (Student value : ss) {
                		taResult.appendText(value.getName() + " ");
                    }
                	taResult.appendText("\n");
                }
                else
                	taResult.appendText("\n指导的学生：无\n");
            }
            else {
            	if(s.getTeacher() == t) {
            		taResult.appendText("添加失败！您已经是他的导师了\n");
            	}
            	else {
            		taResult.appendText("添加失败！该生已经有导师了\n");
				}
			}
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            tx.rollback(); // 回滚事务
            taResult.appendText("添加失败！\n");
            throw e;
        } finally {
            session.close(); // 关闭session
        }
	}
	
	public void btDelStudent4Event(ActionEvent event) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
        try {
        	tx = session.beginTransaction(); // 开启事务
            //具体操作
            Teacher t = session.load(Teacher.class, Long.valueOf(tbID4.getText()));
            Set<Student> ss = t.getStudents();
            Student s = session.load(Student.class, Long.valueOf(tbStudentID4.getText()));
            if(s.getTeacher() == t) {
            	ss.remove(s);
            	s.setTeacher(null);
                t.setStudents(ss);
                taResult.appendText("删除学生成功！\n");
                taResult.appendText("工号：" + t.getId() + "   姓名：" + t.getName());
                if(!ss.isEmpty()){
                	taResult.appendText("\n指导的学生：");
                	for (Student value : ss) {
                		taResult.appendText(value.getName() + " ");
                    }
                	taResult.appendText("\n");
                }
                else
                	taResult.appendText("\n指导的学生：无\n");
            }
            else {
            	taResult.appendText("删除失败！该生的导师不是您\n");
			}
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            tx.rollback(); // 回滚事务
            taResult.appendText("添加失败！\n");
            throw e;
        } finally {
            session.close(); // 关闭session
        }
	}
}
